<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>裁剪图片</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <script type="text/javascript" src="/Public/js/jquery-2.1.4.min.js"></script>
    <script type="text/javascript" src="/Public/js/megapix-image.js"></script>
    <script type="text/javascript" src="/Public/js/hammer.min.js"></script>
    <script type="text/javascript" src="/Public/js/hammer.fakemultitouch.js"></script>
    <script type="text/javascript" src="/Public/js/hammer.showtouches.js"></script>
    <script type="text/javascript" src="/Public/js/exif.js"></script>
    <script type="text/javascript" src="/Public/js/tom-jqplugins.js"></script>
    <script type="text/javascript" src="/Public/js/tom.Lib.js"></script>
    <script type="text/javascript" src="/Public/layer_mobile/layer.js"></script>

    <style type="text/css">
        html,body{
            margin: 0;
            padding: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
        }
        .toBar{
            width: 100%;
            padding: 15px;
            -webkit-box-sizing: border-box;
            box-sizing: border-box;
            position: absolute;
            left: 0;
            bottom: 0;
            z-index: 1;
        }
        .toBar  button{
            display: inline-block;
            width: 100px;
            text-align: center;
            padding: 10px 0;
            font-size: 12px;
            color: #fff;
            background: #8080ca;
            border-radius: 6px;
            cursor: pointer;
        }
        .toBar .right{
            border: none;
            float: right;
        }
        .img_content,canvas{
            position: absolute;
            top: 50%;
            left: 50%;
            -webkit-transform: translate(-50%,-50%);
            transform: translate(-50%,-50%);
        }
        canvas{
            border: 1px solid #333;
        }
        #file{display: none}
    </style>

</head>
<body>

<div class="toBar">
    <button class="left" type="button">取消</button>
    <button class="right" type="button">确定</button>
</div>
<div class="img_content" width="<{$width}>" height="<{$height}>" >
    <img id="old" src=""  />
</div>
<!--裁剪图片框。宽高为定义裁剪出的图片大小-->
<canvas width="<{$width}>" height="<{$height}>" ></canvas>
<input type="file"  id="file"  />
<script>
    /**
     * 图片转base64
     * @param {Object} img
     */
    function img_base64(img,width,height){
        var canvas = document.createElement("canvas");
        canvas.width = width;
        canvas.height = height;
        var c = canvas.getContext("2d");
        c.drawImage(img,0,0,width,height);
        var dataUrl = canvas.toDataURL(img.src,0.8);
        return dataUrl;
    }

    /**
     * base64转blob
     * @param {Object} base64
     */
    function img_blob(base64){
        var dataURI = base64; //base64 字符串
        var mimeString =  dataURI.split(',')[0].split(':')[1].split(';')[0]; // mime类型
        var byteString = atob(dataURI.split(',')[1]); //base64 解码
        var arrayBuffer = new ArrayBuffer(byteString.length); //创建缓冲数组
        var intArray = new Uint8Array(arrayBuffer); //创建视图
        for (i = 0; i < byteString.length; i += 1) {
            intArray[i] = byteString.charCodeAt(i);
        }
        var blob = new Blob([intArray], { type:  mimeString }); //转成blob
        return blob;
    }

    /**
     * 获取本地图片路径
     * @param {Object} selector
     */
    function getFileUrl(selector){
        var img_url;
        if(navigator.userAgent.indexOf("MSIE")>=1){
            img_url = selector.value;
        }else{
            img_url = window.URL.createObjectURL(selector.files.item(0));
        }
        return img_url;
    }

    /**
     * 图片加载
     * @param {Object} img_src
     * @param {Object} callback
     */
    function loadImg(img_src,callback){
        var img = new Image();
        img.src = img_src;
        img.onload = function(){
            callback(img);
        };
    }



    window.addEventListener("load",function(){
        parent.closeLoad();
        var $input  = document.querySelector("#file");
        var $img    = document.querySelector("#old");
             $img.onload=function(){
                 layer.closeAll();
             }
        var $canvas = document.querySelector("canvas");

        //选择图片
        $input.addEventListener("change",function(){
            $img.src    = getFileUrl(this);
            layer.open({
                type: 2
                ,content: '加载中'
            });
        },false);

            document.addEventListener("touchmove", function(e) {
                e.preventDefault();
            });
            var opts = {
                        cropWidth: $canvas.width,
                        cropHeight: $canvas.height
                    };
             var previewStyle = {
                        x: 0,
                        y: 0,
                        scale: 1,
                        rotate: 0,
                        ratio: 1
                    };
              var transform = tomLib.prefixStyle("transform");
              var myCrop = tomLib.cropImage({
                        bindFile: $($input),
                        enableRatio: false, //是否启用高清,高清得到的图片会比较大
                        canvas: $canvas, //放一个canvas对象
                        cropWidth: opts.cropWidth, //剪切大小
                        cropHeight: opts.cropHeight,
                        bindPreview: $("#old"), //绑定一个预览的img标签
                        useHammer: true, //是否使用hammer手势，否的话将不支持缩放
                        oninit: function() {
                        },
                        onLoad: function(data) {
                            //alert(data.width)
                            //alert(data.height)
                            //用户每次选择图片后执行回调
                            resetUserOpts();
                            previewStyle.ratio = data.ratio;
                            $("#old").attr("src", data.originSrc).css({
                                width: data.width,
                                height: data.height
                            }).css(transform, 'scale(' + 1 / previewStyle.ratio + ')');
                            myCrop.setCropStyle(previewStyle)
                        }
                    });

        function resetUserOpts() {
            $("canvas").hammer('reset');
            previewStyle = {
                scale: 1,
                x: 0,
                y: 0,
                rotate: 0
            };
            $("#old").attr("src", '');
        };

        $("canvas").hammer({
            gestureCb: function(o) {
                //每次缩放拖拽的回调
                $.extend(previewStyle, o);
                $("#old").css(transform, "translate3d(" + previewStyle.x + 'px,' + previewStyle.y + "px,0) rotate(" + previewStyle.rotate + "deg) scale(" + (previewStyle.scale / previewStyle.ratio) + ")")
            }
        });

        $(".right").on("click", function() {
            layer.open({
                type: 2
                ,content: '图片正在压缩上传中。。。'
            });
            myCrop.setCropStyle(previewStyle)
            var src = myCrop.getCropFile({});
                $.post('./api.php?m=Api&c=index&a=base64upload&from=<{$imgType}>', {dataURL: src}, function (ans) {
                    console.log(ans)
                    if (ans.status==0) {
                        parent.editImg(ans.url);
                        resetCanvas();
                    }
                }, 'json');
        });

        $(".left").on("click", function() {
            resetCanvas();
        });

        function resetCanvas(){
            parent.load()
            location.reload();
            parent.closeIframeCut();
        }

    },false);

</script>

</body>
</html>